我想请求帮助。
我的数据库中有3个表:
表'用户':
|ID| Name| Surname| Status |
----------------------------------
|14 | Joe| Smith| 1 |
|15 | Paul| Taylor| 1 |
|16 | Martin| List| 1 |
表'user_data':
|IDuser| IDciselnik| skUserValue|
--------------------
|14 | 1| value1 text Joe|
|14 | 3| value3 text Joe|
|14 | 4| 25|
|15 | 1| value1 text Paul|
|15 | 3| value3 text Paul|
|15 | 4| 26|
|16 | 1|value1 text Martin|
|16 | 3|value3 text Martin|
|16 | 4| 22|
表'ciselnik':
|ID| skTitle|
--------------------
|25 | Kosice|
|26 | Skošicel|
|22 | Prague|
如果我想获得如下所示的输出,请与所有用户一起使用:
输出:
|userID | Name | Surname | value_ID1 | value_ID3 |
------------------------------------------------------------------
| 14 | Joe | Smith | value1 text Joe | value3 text Joe |
| 15 | Paul | Taylor | value1 text Paul | value3 text Paul |
| 16 | Martin | List | value1 text Martin | value3 text Martin |
我知道我可以得到:
SELECT us.ID AS userID, us.Name, us.Surname,
max(CASE WHEN ud.IDciselnik =1 THEN ud.skUserValue END) value_ID1,
max(CASE WHEN ud.IDciselnik =3 THEN ud.skUserValue END) value_ID3
FROM user_data ud LEFT JOIN Users us ON us.ID = ud.IDuser
WHERE us.Status=1
GROUP BY us.ID ORDER BY value_ID3 DESC
但是,我有搜索按钮,我想只过滤“kosice”或类似名称的用户。 首先,我需要从“ciselnik”表中获取“kosice”存在的所有ID 然后来自'ciselnik'的ID我需要检查/比较哪个用户拥有它,并且只选择skUserValue等于'ciselnik'的用户
简单地在我的输出中我不需要获得所有用户,但是在输出示例中:
|userID | Name | Surname | value_ID1 | value_ID3 | skTitle |
------------------------------------------------------------------
| 14 | Joe | Smith | value1 text Joe | value3 text Joe | Kosice |
| 15 | Paul | Taylor | value1 text Paul | value3 text Paul | Skošicel |
我用过这个
SELECT us.ID AS userID, us.Name, us.Surname, c.skTitle,
max(CASE WHEN ud.IDciselnik =1 THEN ud.skUserValue END) value_ID1,
max(CASE WHEN ud.IDciselnik =3 THEN ud.skUserValue END) value_ID3
FROM user_data ud LEFT JOIN Users us ON us.ID = ud.IDuser
LEFT JOIN ciselnik c ON c.ID = ud.skUserValue
WHERE us.Status=1
AND c.skTitle COLLATE utf8_general_ci LIKE '%kosice%'
GROUP BY us.ID ORDER BY value_ID3 DESC
我现在有问题,在我的输出中:value_ID1和value_ID3为NULL 谢谢你的帮助
答案 0 :(得分:0)
那将是
SELECT u.Name, u.Surname, d1.skUserValue AS value_ID1, d3.skUserValue AS value_ID3
FROM Users u
LEFT JOIN user_data d1 ON u.IDuser = u.ID AND d1.IDciselnik =1
LEFT JOIN user_data d3 ON u.IDuser = u.ID AND d3.IDciselnik =3
LEFT JOIN user_data d4 ON u.IDuser = u.ID AND d4.IDciselnik =4
LEFT JOIN ciselnik c ON d4.skUserValue = c.ID
WHERE c.skTitle LIKE '%blah%'
通过在不同的别名下加入数据表,您可以按连接条件中的id过滤每个子集。