如何选择包含Y优先和N秒的mysql列值

时间:2018-04-01 17:24:49

标签: mysql

我想在mysql中查询以选择包含Y和N的列值。 下面是我的表

enter image description here

如果我使用此查询

import UIKit
import AVFoundation
import Firebase

class ProductViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    @IBOutlet weak var idLabel: UILabel!

    var passStuff: productsList?

    var updater: productsList?

    override func viewDidLoad() {
        super.viewDidLoad()

        idLabel.text = updater?.id
    }

    var player : AVPlayer!

    let url = "http://listen.shoutcast.com/radiodeltalebanon"

    @IBAction func playThis(_ sender: Any) {

        print("Something is playing")
    }
    @IBAction func pauseBtn(_ sender: Any) {
        player.pause()
    }
}

enter image description here

这个查询是基于插入ID工作的,但是我的要求不是那样的,首先它应该首先选择'Y'然后才应该'N'。

[![在此处输入图像说明] [3]] [3]

我想要选择特定的这些列值
2 ---- 123 ------ Y
4 ----- 324 ------ Y
6 ----- 456 ------ N或5 ------ 456 - N从N出现的任何一行 7 ----- 987 ------ Y

提前致谢!!!

3 个答案:

答案 0 :(得分:1)

我之前的回答有一个问题,表明在MySql中执行查询时与only_full_group_by有关的错误。但是,我自己创建了一个本地数据库,然后想出了你需要的正确的sql。这里是。

SELECT min(origin), hotel_code, max(standard) as std from hotel 
    where standard='Y' OR standard='N' 
    group by hotel_code 
    order by std desc;

执行sql之后,我得到了结果。

1   123     Y
3   324     Y
7   987     Y
5   456     N

我正在共享create table和insert语句,以便任何人都可以自己检查查询是否正常。

create table hotel (
    origin integer auto_increment primary key,
    hotel_code integer not null, 
    standard varchar(1) not null
);

INSERT INTO `hotel` (`origin`, `hotel_code`, `standard`)
VALUES
    (1, 123, 'Y'),
    (2, 123, 'N'),
    (3, 324, 'N'),
    (4, 324, 'Y'),
    (5, 456, 'N'),
    (6, 456, 'N'),
    (7, 987, 'N'),
    (8, 987, 'Y');

希望有所帮助!

答案 1 :(得分:0)

这里你需要的是:

SELECT origin, hotel_code, CASE COUNT(DISTINCT standart)
  WHEN 1 AND standart = "N" THEN "N"
  WHEN 1 AND standart = "Y" THEN "Y"
  WHEN 2 THEN "Y"
END as standart
FROM hotel
GROUP BY hotel_code ORDER BY standart DESC

结果:

origin  hotel_code  standart
1   123     Y
3   324     Y
9   888     Y
7   987     Y
6   456     N

SQLFiddle:http://sqlfiddle.com/#!9/17bd53/3/0

答案 2 :(得分:0)

有许多方法可以解决您的算法,但是,由于简单,我选择了这个:

SELECT h2.origin,h2.hotel_code,h2.standard
FROM SELECT * FROM 酒店 WHERE 标准='Y')h1
h1.hotel_code = h2.hotel_code的加入酒店h2 ORDER BY h2.hotel_code,h2.standard;

Click here to view it working

享受它!