MySQL查询 - 有点棘手

时间:2014-02-10 14:45:03

标签: php mysql mysqli

我有以下表格:

USERS:                               ITEMS

user_id  name    always_show         id   user_id  name
--------------------------           --------------------------------
1        Joe                         1    1        Apple   
2        Sam                         2    1        Banana
3        Walter  1                   3    2        Cherry

我在做这个查询:

SELECT * FROM
  users Inner Join
  items On users.user_id = items.user_id

问题是:我如何添加所有其他具有标记always_show设置的用户?

3 个答案:

答案 0 :(得分:1)

我希望我理解你的问题:-)试试UNION

SELECT u.* FROM users u
INNER JOIN items i ON u.user_id = i.user_id

UNION ALL SELECT * FROM users WHERE always_show = 1

答案 1 :(得分:0)

SELECT * 
FROM users 
INNER JOIN items On users.user_id = items.user_id
UNION
SELECT * 
FROM users 
LEFT OUTER JOIN items On users.user_id = items.user_id AND users.always_show = 1

答案 2 :(得分:0)

SELECT * FROM
  users Inner Join
  items On users.user_id = items.user_id where Users.always_set = 1