MySQL在字段中使用select子查詢

2021-08-03 02:41:30 字數 2424 閱讀 8837

前幾天看別人的**中看到在字段中使用select子查詢的方法,第一次見這種寫法,然後研究了一下,記錄下來

大概的形式是這樣的:

select a .*,(select b.another_field from b where a.id=b.aid) another_field from a where 1 limit 10;

商品表:

[sql]view plain

copy

create

table

`product` (  

`id` int

(11) 

notnull

auto_increment,  

`product_name` varchar

(30) 

character

setutf8 

notnull

,  `price` float

notnull

,  primary

key(`id`)  

) engine=innodb;  

[sql]view plain

copy

create

table

`comment` (  

`id` int

(11) 

notnull

auto_increment,  

`entity_id` int

(11) 

notnull

,  `content` varchar

(100) 

character

setutf8 

notnull

,  primary

key(`id`)  

) engine=innodb;  

然後插入一些資料:

[sql]view plain

copy

insert

into

`product` (`id`, `product_name`, `price`) 

values

(1, '肉鬆餅'

, 5),  

(2, '可樂'

, 5),  

(3, '雞翅'

, 12),  

(4, '杯子'

, 42);  

insert

into

`comment` (`id`, `entity_id`, `content`) 

values

(1, 1, '味道還不錯'

),  

(2, 1, '還行啊'

),  

(3, 3, '很實用哦'

);  

[sql]view plain

copy

select

product.*,(

select

count

(comment.id) 

from

comment 

where

product.id=comment.entity_id) comment_count 

from

`product` limit 5;  

查詢結果如下:

idproduct_name

price

comment_count

1 肉鬆餅5  2

2 可樂5  0

3 雞翅12  1

4 杯子42  0

對於這種查詢,可以分成兩部來理解,首先忽略整個select子查詢,查出商品表中的資料,然後根據商品的id執行子查詢,對於乙個商品id,子查詢只能返回一條資料,如果子查詢返回多條資料則會出錯,另外,每一條select子查詢只能查詢乙個字段。

[sql]view plain

copy

select

product.*,(

select

comment.content 

from

comment 

where

product.id=comment.entity_id 

order

bycomment.id 

desc

limit 1) comment_count 

from

`product` limit 5;  

查詢結果如下:

idproduct_name

price

last_comment

1 肉鬆餅5  還行啊

2 可樂5

null

3 雞翅12  很實用哦

4 杯子42

null

在oracle中使用自增字段

大家都知道,oracle是不支援auto increment欄位的,但可以通過建立sequence物件來使用自增序列,語法是 sql create sequence seq subs id increment by1 start with 1 maxvalue 10000000000 nocycle...

在MySQL中使用memcached

這裡提供了一組mysql的udf函式,可以直接在sql中操作memcached。安裝比較簡單,需要安裝 libmemcached 0.12.tar.gz,然後安裝 memcached functions mysql 0.1.tar.gz就可以了。它的幫助檔案中提供了使用方法。只是需要設定ld lib...

在Python中使用MYSQL

緣由 近期在折騰乙個小東西須要抓取網上的頁面。然後進行解析。將結果放到 資料庫中。了解到python在這方面有優勢,便選用之。由於我有臺 server上面安裝有 mysql,自然使用之。在進行資料庫的這個操作過程中遇到了不少問題,這裡 記錄一下,大家共勉。python中mysql的呼叫 之後能夠通過...