简体   繁体   English

MySQL在单个查询中具有不同位置的多重选择

[英]MySQL multiple select with different wheres in single query

First of, at the moment I am forced to use MySQL despite it being deprecated. 首先,尽管我不推荐使用MySQL,但目前我仍然被迫使用它。 I am very well aware of that fact. 我非常清楚这个事实。 Hopefully you guys can still help me with my sql syntax. 希望你们仍然可以用我的sql语法帮助我。

I am trying to access several columns from some different tables. 我试图从一些不同的表中访问几列。 Problem is, some of the columns require a different where clause than the last column I need, and the where clause for the last column requires info from the rest of the query so I cannot split it up into multiple queries, I've tried. 问题是,有些列与我需要的最后一列要求的where子句不同,并且最后一列的where子句需要来自其余查询的信息,因此我无法将其拆分为多个查询。

I cannot use union because one select statement selects four columns, and the other one selects one column. 我不能使用并集,因为一个选择语句选择四列,而另一个选择一个列。

Query: 查询:

(SELECT DISTINCT inventory.Quantity, itemtypes.Itemtypename, 
itemtypes.ItemtypeID, inventory.ItemID
FROM inventory JOIN itemtypes ON inventory.ItemtypeID = itemtypes.ItemtypeID
JOIN sets ON inventory.SetID = sets.SetID
WHERE inventory.ItemtypeID = itemtypes.ItemtypeID
AND itemtypes.Itemtypename = 'Set'
AND sets.SetID = '".$setid."')
UNION
(SELECT DISTINCT sets.Setname
FROM sets JOIN inventory ON sets.SetID = inventory.ItemID
WHERE sets.SetID = inventory.ItemID)

This is what I tried to use, with no success. 这是我尝试使用的方法,但没有成功。 I cannot seem to find any other way of linking to different select statements without using multiple queries (with due to the structure of my PHP file, is impossible to do properly). 我似乎找不到不使用多个查询就可以链接到不同的select语句的任何其他方式(由于我的PHP文件的结构,无法正确执行)。 The rest of the file will work, if only this problem gets solved. 如果仅解决此问题,则文件的其余部分将起作用。 Hopefully you guys can help me with this, please let me know if this is even possible to do. 希望你们可以帮助我,请告诉我是否可以这样做。 Let me know if you need to see my PHP code as well. 让我知道您是否也需要查看我的PHP代码。 $setid is derived from a get in the file and contains a value existing in the database. $ setid是从文件中的get派生的,并且包含数据库中存在的值。

May be, you can try like this. 可能是,您可以尝试这样。 It works fine in SQL Server. 它在SQL Server中工作正常。

SELECT TMP1.Quantity,TMP1.Itemtypename, TMP1.ItemtypeID, TMP1.ItemID, TMP2.Setname
FROM(
SELECT DISTINCT 
inventory.Quantity, 
itemtypes.Itemtypename, 
itemtypes.ItemtypeID, 
inventory.ItemID
FROM inventory 
JOIN itemtypes ON inventory.ItemtypeID = itemtypes.ItemtypeID
JOIN sets ON inventory.SetID = sets.SetID
WHERE inventory.ItemtypeID = itemtypes.ItemtypeID
AND itemtypes.Itemtypename = 'Set'
AND sets.SetID = '".$setid."'
) AS TMP1,
(
SELECT DISTINCT 
sets.Setname
FROM sets 
JOIN inventory ON sets.SetID = inventory.ItemID
WHERE sets.SetID = inventory.ItemID
) AS TMP2

Hope this is what you want. 希望这就是你想要的。 Your question seems very ambiguous. 您的问题似乎很含糊。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM