我试图在两个简单的表上写一个查询。表很简单,查询不是:)
以下是表格内容的概述:
我试图写一个查询,列出相应表格中的所有资产,只有当标记为"想要" (意思是布尔字段asset_owned = 0)并且为另一个所有者引用为"拥有"。
这是我到目前为止所做的工作:
SELECT
user.user_pseudo AS REQUESTER,
asset.asset_sku AS SKU,
asset.asset_name AS ASSET_NAME
FROM
asset
INNER JOIN user ON asset.id_user = user.id
WHERE
asset.asset_owned = 0
AND
asset.asset_sku IN (SELECT asset.asset_sku FROM asset WHERE asset.asset_owned = 1)
但是,在同一个查询中(如果可能的话)我也希望获得所有者名称。
在这些表上进行此类查询的第一个结果是:
我,003,Test003,你。
我尝试过内联SELECT和嵌套子查询,如:
SELECT
user.user_pseudo as ASKER,
asset.asset_sku as SKU,
asset.asset_name as NAME,
subquery1.user.user_pseudo as OWNER
FROM
asset
INNER JOIN user ON asset.id_user = user.id,
(SELECT user.user_pseudo.asset_asset_sku FROM asset INNER JOIN user ON asset.id_user = user.id WHERE asset.asset_owned = 1) subquery1
WHERE
asset.asset_owned = 0 AND
subquery1.asset.asset_sku IN (SELECT asset.asset_sku FROM asset INNER JOIN user ON asset.id_user = user.id WHERE asset.asset_owned=1)
但当然这不起作用。
感谢您指点我的任何方向。
新年快乐的Mathias
答案 0 :(得分:2)
所以这对我来说很有趣(我学习SQL,所以这是一个好习惯!) - 我很欣赏这个非常明确的问题。
希望这适合您 - 我使用了两个子查询(一个用于'所有者'以及'请求者')然后加入了SKU和名称上的子查询。它可以在SQLite中使用上面显示的小样本数据。
SELECT requester, subq1.SKU, subq1.name, owner
FROM
(SELECT pseudo AS requester, SKU, name
FROM asset, user
WHERE owned = 0
AND user.id = id_user) subq1,
(SELECT pseudo AS owner, SKU, name
FROM asset, user
WHERE owned = 1
AND asset.id_user = user.id) subq2
WHERE subq1.SKU = subq2.SKU
AND subq1.name = subq2.name;