我有一个名为USERS
的表和一个名为ADDRESSES
的表,还有一个ADDRESS_TYPE
表。每个用户可以有多个地址。
SELECT *
FROM USER
INNER JOIN address ON address.userId = user.userId
INNER JOIN address_type ON address_type.id = address.addressType
WHERE addressType = 4
OR primaryAddress = 1
如果addressType为4,我想将address表连接到user表,但是如果addressType不是4,则应该拉入标记为primary的地址。基本上,问题是我需要对查询进行分组,这样每个用户只得到一行,同时具有逻辑“如果addressType=4,则加入此地址,否则如果primaryAddress=1,则加入此其他地址”。
希望这有意义,非常感谢任何帮助。
编辑:这些是我要处理的表格:
用户表
+--------+-----------------+-----------------+
|用户名|
+--------+-----------------+-----------------+
|10001 |黛比|巴森|
|10002 |巴马瓦马|库登|
|10003 |杰西卡姆|斯蒂维斯|
|10004 |金农|白|
+--------+-----------------+-----------------+
地址类型
+----+------+-------------+------------+------------+
|id |代码|说明|可修改|数据状态|
+----+------+-------------+------------+------------+
|1 |家|家| 1 | 1|
|2 |公交车|商务| 1 | 1|
|3 |学校| 1 | 1|
|4 |堂|捐赠人地址| 1 | 1|
+----+------+-------------+------------+------------+
地址表
+----------------+--------+-------------------------+-------------+-------------+
|主要地址|用户ID |街道1 |城市|地址类型|
+----------------+--------+-------------------------+-------------+-------------+
|0 | 10001 | 12660皮卡特广场|圣地亚哥| 1|
|威尔希尔大道西446号富勒顿2号,邮编:0 | 10001 ||
|0 | 10001 | 4224东114路|桑顿| 3|
|科罗拉多大道828号1 | 10001 |。|洛杉矶| 4|
|0 | 10002 | 40A林登大道#2 |萨默维尔| 1|
|0 | 10002 | 446 37街#2 |奥克兰|无效|
|1 | 10002 |邮政信箱06562 |芝加哥|无效|
|0 | 10002 | 1281 W.2nd St.| San Pedro |空|
|1 | 10003 | 10557 S.Oakley Ave.| Chicago |无效|
|0 | 10003 | 1425哈里森街#324 |奥克兰|无效|
+----------------+--------+-------------------------+-------------+-------------+
最佳答案
这就是你要找的吗?
SELECT *
FROM USER
INNER JOIN address ON address.userId = user.userId
INNER JOIN address_type ON address_type.id = address.addressType
WHERE addressType = 4
OR NOT EXISTS
(SELECT addressType FROM USER
INNER JOIN address ON address.userID = user.userID
INNER JOIN address_type ON address_type.id = address.addressType
WHERE addressType = 4)
AND primaryAddress = 1
关于mysql - 有条件地加入MySQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13130276/