我正在尝试这个Mysql查询 -
SELECT pan_1, dp_id, client_id, CONCAT(dp_id,client_id) AS ref, name_s, bonds
FROM `holding_details`
WHERE `date` = '2015-10-23'
AND comp_code = '33'
AND ref NOT IN
(SELECT CONCAT(dp_id,client_id) AS ref FROM `promoters` WHERE comp_code = '33')
GROUP BY pan_1
ORDER BY bonds DESC
通过阅读上述查询,您只需了解我想要的结果。我在两个名称相同的表中都有两个saparate列dp_id和client_id。我想从' holding_details'中得到一些结果。除了“促销员”中存在的那些之外的表格。在dp_id和client_id列的条件下,我将它们组合在一起,因为它使它们成为唯一记录。我尝试了上面的MySql查询,但它显示了我"未知列ref"错误。请告诉我在同一个查询中不可能使用combine列,如何实现该结果。谢谢
答案 0 :(得分:1)
您可以使用NOT EXISTS
:
SELECT pan_1, dp_id, client_id, CONCAT(dp_id,client_id) AS ref, name_s, bonds
FROM `holding_details` d
WHERE `date` = '2015-10-23'
AND comp_code = '33'
AND NOT EXISTS
(SELECT 'x' FROM `promoters` p
WHERE p.comp_code = '33'
AND p.dp_id = d.dp_id
AND p.client_id = d.client_id)
GROUP BY pan_1
ORDER BY bonds DESC
这也应该有效:只指定两列(没有CONCAT!),并从select中返回两列:
SELECT pan_1, dp_id, client_id, CONCAT(dp_id,client_id) AS ref, name_s, bonds
FROM `holding_details`
WHERE `date` = '2015-10-23'
AND comp_code = '33'
AND (dp_id, client_id) NOT IN
(SELECT dp_id, client_id) AS ref FROM `promoters` WHERE comp_code = '33')
GROUP BY pan_1
ORDER BY bonds DESC
如果您不使用别名ref
,那么您自己的尝试也可能有效,但表达式本身也是如此。不过,我更喜欢上面的那个。 Concatting使得索引的使用不那么清晰,效率也会降低。如果您有正确的索引,上面的查询可以非常有效。无论如何,这是:
SELECT pan_1, dp_id, client_id, CONCAT(dp_id,client_id) AS ref, name_s, bonds
FROM `holding_details`
WHERE `date` = '2015-10-23'
AND comp_code = '33'
AND CONCAT(dp_id,client_id) NOT IN
(SELECT CONCAT(dp_id,client_id) AS ref FROM `promoters` WHERE comp_code = '33')
GROUP BY pan_1
ORDER BY bonds DESC
答案 1 :(得分:1)
不完全是你的问题的答案,但可能是你的问题....... 更好地使用NOT EXIST。它使用索引的机会比你的CONCAT()方法更好......
SELECT
pan_1, dp_id, client_id, name_s, bonds
FROM
`holding_details` as hd
WHERE
hd.`date` = '2015-10-23'
AND
hd.comp_code = '33'
AND
NOT EXISTS (
SELECT
*
FROM
promoters as p
WHERE
p.comp_code = '33'
AND hd.dp_id=p.dp_id
AND hd.client_id=p.client_id
)
GROUP BY
pan_1
ORDER BY
bonds DESC
答案 2 :(得分:0)
尝试此查询,
SELECT pan_1, hd.`dp_id`, hd.`client_id`, CONCAT(hd.`dp_id`,hd.`client_id`) AS ref, name_s, bonds
FROM `holding_details` as hd
LEFT JOIN `promoters` as p on p.`dp_id` = hd.`dp_id` AND p.`client_id` = hd.`client_id`
WHERE hd.`date` = '2015-10-23'
AND hd.`comp_code` = '33'
AND p.`dp_id` <> hd.`dp_id`
AND p.`client_id` <> hd.`client_id`
GROUP BY pan_1
ORDER BY bonds DESC