简体   繁体   English

如何在MySQL中使用子查询

[英]How to use subqueries in MySQL

I have two tables. 我有两张桌子。

Table user : 用户

CREATE TABLE IF NOT EXISTS `user` (
  `user_id` int(20) NOT NULL AUTO_INCREMENT,
  `ud_id` varchar(50) NOT NULL,
  `name` text NOT NULL,
  `password` text NOT NULL,
  `email` varchar(200) NOT NULL,
  `image` varchar(150) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB

and mycatch : mycatch

CREATE TABLE IF NOT EXISTS `mycatch` (
  `catch_id` int(11) NOT NULL AUTO_INCREMENT,
  `catch_name` text NOT NULL,
  `catch_details` text NOT NULL,
  `longitude` float(10,6) NOT NULL,
  `latitude` float(10,6) NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `image` varchar(150) NOT NULL,
  `user_id` int(20) NOT NULL,
  PRIMARY KEY (`catch_id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB;
ALTER TABLE `mycatch`
  ADD CONSTRAINT `mycatch_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;

My goal is: I want to retrieve longitude and latitude from mycatch against given ud_id (from user ) and catch_id (from mycatch ) where ud_id = given ud_id and catch_id > given catch_id . 我的目标是:我想针对给定的ud_id (来自user )和catch_id (来自mycatch )从mycatch检索经度和纬度,其中ud_id =给定的ud_idcatch_id >给定的catch_id

I used the query but fail to retrieve 我使用了查询但无法检索

SELECT ud_id=$ud_id FROM user
WHERE user_id =
(
SELECT user_id,longitude,latitude from mycatch
WHERE catch_id>'$catch_id'
)

The error is: 错误是:

#1241 - Operand should contain 1 column(s) #1241-操作数应包含1列

First, try not to use subqueries at all, they're very slow in MySQL. 首先,尽量不要使用子查询,在MySQL中它们非常慢。

Second, a subquery wouldn't even help here. 其次,子查询甚至在这里都无济于事。 This is a regular join (no, Mr Singh, not an inner join): 这是常规联接(不,辛格先生,不是内部联接):

SELECT ud_id FROM user, mycatch
WHERE catch_id>'$catch_id'
AND user.user_id = mycatch.user_id
 Select m.longitude,m.latitude from user u left join mycatch m 
on u.user_id =m.user_id 
where u.ud_id=$ud_id and 
m.catch_id >$catch_id

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

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