数据库不是我的。结构是
fid| uid | value
3 | 3 | spain
3 | 5 | France
2 | 3 | 45
6 | 3 | male
6 | 5 | female
2 | 5 | 32
字段ID是另一个表中的主键,我想忘记。 我试图找到所有有价值'西班牙','男性'的uid
我有以下工作。
SELECT uid
FROM DATABASE
WHERE value IN ('spain', 'male') GROUP BY uid HAVING COUNT(*) >= 2
捕获如下:我如何选择雄性,西班牙的值在20-30范围内 (那是在西班牙出生的年龄在20-30岁之间的男性?
非常感谢!!
答案 0 :(得分:1)
使用自我加入:
SELECT tland.uid
FROM `table` AS tland
INNER JOIN `table` AS tgender ON tland.uid = tgender.uid
INNER JOIN `table` AS tage ON tland.uid = tage.uid
WHERE tland.value = 'spain'
AND tgender.value = 'male'
AND 20 <= tage.value AND tage.value <= 30
答案 1 :(得分:1)
你有一张非常乱糟糟的桌子。你正在混合不相关的东西。
尝试:
SELECT uid
FROM DATABASE a JOIN
DATABASE b USING (uid)
WHERE a.value IN ('spain', 'male')
AND b.value >= 20
AND b.value <= 30
GROUP BY uid
HAVING COUNT(*) >= 2
请注意,我正在比较字符串和整数。您将需要进行测试,看看它的效果如何。
另外,我只是把西班牙和男性放在一起,但也许他们真的无关?
fid是否决定了值的类型?
尝试:
SELECT uid
FROM DATABASE country
JOIN DATABASE gender USING (uid)
JOIN DATABASE age USING (uid)
WHERE
country.fid = 3 AND
gender.fid = 6 AND
age.fid = 2 AND
county.value = 'spain' AND
gender.value = 'male' AND
age.value >= 20
age.value <= 30
GROUP BY uid
HAVING COUNT(*) >= 2
此代码应该更可靠。
答案 2 :(得分:0)
这样可行。
SELECT d1.uid FROM demo d1
INNER JOIN demo d2 ON d2.uid = d1.uid AND d2.fid = 6 AND d2.value = "Male"
INNER JOIN demo d3 ON d3.uid = d1.uid AND d3.fid = 3 AND d3.value = "Spain"
WHERE (d1.fid = 2 AND (d1.value BETWEEN 20 AND 30))
答案 3 :(得分:0)
保持语法尽可能接近,这可能有效:
SELECT uid
FROM database
WHERE value in ('spain', 'male') or convert(value, , SIGNED INTEGER) between 30 and 50
GROUP BY uid HAVING COUNT(*) >= 3
答案 4 :(得分:0)
由于您的字段被映射为:
fid 3 = country
fid 2 = age
fid 6 = sex
您可以将该表转换为更符合逻辑的视图(在UID上编制索引)
(SELECT c.uid, c.country, a.age, s.sex FROM
(SELECT uid, value AS country FROM maintable WHERE fid = 3) c INNER JOIN
(SELECT uid, value AS age FROM maintable WHERE fid = 2) a ON c.uid = a.uid INNER JOIN
(SELECT uid, value AS sex FROM maintable WHERE fid = 6) s ON c.uid = s.uid
) as X
一旦它进入视图,您就可以将数据视为常规表。我假设你可能有超过3种类型的数据,因为你的例子中fid最多可达6个。
假设您已将其放入视图(称为X),您可以这样做:
SELECT * FROM X
WHERE age BETWEEN 20 AND 30
AND country = 'spain'
AND sex = 'male'