使用子查询时无法选择id

时间:2017-04-21 06:51:26

标签: mysql

这是我当前的查询,返回text列作为结果。

SELECT text FROM `tableA` WHERE EXISTS (SELECT id FROM tableA WHERE `id` LIKE '%00%') GROUP BY text

但我也希望id被选中,但我的下面的查询会出错,我不知道为什么。 (也选择了ID ID)

SELECT id, text FROM `tableA` WHERE EXISTS (SELECT id FROM tableA WHERE `id` LIKE '%00%') GROUP BY text


Error:
#1055 - Expression #1 of SELECT list is not in GROUP BY 
clause and contains nonaggregated column 
'search_db.tableA.id' which is not
functionally dependent on columns in GROUP BY clause; 
this is incompatible with sql_mode=only_full_group_by

我的完整查询如下所示:

我实际上是从多个表中选择列文本,并希望文本列的唯一值

SELECT DISTINCT text FROM `tableA` AS `table` WHERE EXISTS (SELECT * FROM tableA WHERE `id` LIKE '%0.219%') UNION 
SELECT DISTINCT text FROM `tableB` AS `table` WHERE EXISTS (SELECT * FROM tableB WHERE `id` LIKE '%0.219%') UNION
SELECT DISTINCT text FROM `tableC` AS `table` WHERE EXISTS (SELECT * FROM tableC WHERE `id` LIKE '%0.219%')

2 个答案:

答案 0 :(得分:1)

  

这与sql_mode = only_full_group_by

不兼容

这意味着如果您还要提取id,则应在id语句中添加group by

SELECT id, text
FROM `tableA`
WHERE EXISTS (SELECT id FROM tableA WHERE `id` LIKE '%00%')
GROUP BY id, text

或者您可以从sql_mode中删除only_full_group_by

set @@GLOBAL.sql_mode = replace(@@GLOBAL.sql_mode, 'ONLY_FULL_GROUP_BY', '');

可能在当前会话中修改sql_mode更好:

set @@session.sql_mode = replace(@@session.sql_mode, 'ONLY_FULL_GROUP_BY', '');

答案 1 :(得分:0)

 SELECT id, text FROM `tableA` WHERE `id` LIKE '%00%' GROUP BY text