I'm trying some consultations and I can not get one to work for me. I need to get the list of orders each of which with the name of the associated carrier . I only have 8 orders so I should have 8 results but it returns a lot more ...
SQL create tables:
CREATE TABLE carriers (
id_carrier int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE orders (
id_order int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
reference varchar(9) DEFAULT NULL,
id_carrier int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE orders
ADD UNIQUE(reference),
ADD FOREIGN KEY (id_carrier) REFERENCES carriers(id_carrier);
SQL inserts for tests:
INSERT INTO carriers ( id_carrier , name ) VALUES
(NULL, 'test'),
(NULL, 'seur'),
(NULL, 'asm'),
(NULL, 'xxx');
INSERT INTO orders ( id_order, reference, id_carrier ) VALUES
(NULL, 'XKBKNABJK', 1),
(NULL, 'OHSATSERP', 2),
(NULL, 'UOYEVOLIT', 2),
(NULL, 'FFATNOMMJ', 1),
(NULL, 'KHWLILZLL', 4),
(NULL, 'ZRIIQDSYN', 1),
(NULL, 'DGAJIPUWH', 3),
(NULL, 'RTJHJMRAC', 3);
I was trying different combinations with the following:
SELECT DISTINCT
id_order AS Pedido,
reference AS Referencia,
carriers.name AS Servicio
FROM orders, carriers
WHERE orders.id_carrier IN (SELECT id_carrier FROM carriers)
/*GROUP BY orders.id_order, Servicio*/
ORDER BY orders.id_order ASC