MySQL查询来自两个表,多个加入

时间:2014-03-06 10:10:49

标签: php mysql

我有两张桌子,例如 - category & items.

 1. category table has two fields- cat_id, cat_name.
 2. items table has 4 fields field1, field2, field3, field4 which value
    is cat_id.

现在,我需要在每行中打印cat_name而不是cat_id。

我该怎么做?什么是MySQL查询?

如需了解更多信息,请点击此处 - 网址:http://smartmux.com/demo_roundflat/admin/ 用户名:test 密码:测试

4 个答案:

答案 0 :(得分:1)

您需要使用Join,您的查询应如下所示:

"select t1.*, t2.cat_name FROM table1 as t1 JOIN table2 as t2 on t1.cat_id=t2.cat_id";

答案 1 :(得分:1)

SELECT c.id as cat_name  from category as c , items as i where c.id=i.cat_id

答案 2 :(得分:0)

SELECT 
    category.cat_name
FROM
    category
        JOIN
    items ON category.cat_id = items.field4

答案 3 :(得分:0)

如果我理解得对,你可以这样做:

SELECT items.*, c1.cat_name, c2.cat_name, c3.cat_name, c4.cat_name
FROM items
LEFT JOIN category AS c1 ON c1.cat_id = items.field1
LEFT JOIN category AS c2 ON c2.cat_id = items.field1
LEFT JOIN category AS c3 ON c3.cat_id = items.field1
LEFT JOIN category AS c4 ON c4.cat_id = items.field1;

请告诉我这是否是你需要的。