SELECT-太多行

时间:2019-08-03 12:01:05

标签: sql database postgresql

让我为您展示有关数据库结构的简单演示:

Database structure

  

查询参数:

     

-id_category

     

-id_language

     

-id_account

我需要从wordconfigs表中选择所有行,其中id_wordconfig与存储在hiddenwords表中的id_wordconfig不同。

例如wordconfigs表的cointains:

  

id_wordconfig = 1(此行与以下顺序相关: id_account = 1   (最重要的是1),id_language = 1,id_category = 1)

     

id_wordconfig = 2(此行与以下顺序相关: id_account = 1   (最重要的是1),id_language = 1,id_category = 1)

我将参数传递给查询:

  

-id_category = 1

     

-id_language = 1

     

-id_account = 2(在示例中未分配给wordconfig)

示例1

hiddenwords表为空->查询返回ID为1和2的wordconfid

示例2

hiddenwords表包含:

  

id_hiddenwords = 1; id_wordconfig = 1; id_account = 1

查询还会返回ID为1和2的wordconfig(因为id_account与传递给查询的内容不同)

示例3

hiddenwords表包含:

  

id_hiddenwords = 1; id_wordconfig = 1; id_account = 2

查询仅返回ID为2的wordconfig(因为隐藏的单词像传递给查询一样包含id_wordconfig = 1和id_account = 2)

示例4

hiddenwords表包含:

  

id_hiddenwords = 1; id_wordconfig = 1; id_account = 2

     

id_hiddenwords = 1; id_wordconfig = 2; id_account = 1(与传递给查询的值不同)

查询仅返回id = 2的wordconfig

示例5

hiddenwords表包含:

  

id_hiddenwords = 1; id_wordconfig = 1; id_account = 2

     

id_hiddenwords = 1; id_wordconfig = 2; id_account = 2

查询什么也不会返回

我为此任务创建了一个简单查询:

SELECT wc.*
FROM categorywordconfig cwc, categories c, languages l, accounts a, wordconfigs wc
LEFT JOIN hiddenwords hw ON hw.id_wordconfig<>wc.id_wordconfig
WHERE wc.id_wordconfig=cwc.id_wordconfig
AND cwc.id_category=c.id_category
AND c.id_language=l.id_language
AND l.id_account=a.id_account
AND c.id_category=1
AND l.id_language=1
AND hw.id_account=2

给定查询适用于从1到4的示例。示例5应该什么也不返回,但是通过此查询,它返回所有行(因此idconfig为id 1和2的wordconfig)为什么会这样?怎么了?

编辑: 我只是简单地将查询更改为:

SELECT wc.* FROM categorywordconfig cwc, categories c, languages l, accounts a, wordconfigs wc
WHERE wc.id_wordconfig=cwc.id_wordconfig
AND cwc.id_category=c.id_category AND c.id_language=l.id_language
AND l.id_account=a.id_account AND c.id_category=1 AND l.id_language=1 
AND wc.id_wordconfig NOT IN (SELECT id_wordconfig FROM hiddenwords WHERE id_account=2)

它正在工作:)

0 个答案:

没有答案