I have the following table:
CREATE TABLE `vendor_contacts` (
`vendor_id` int(11) NOT NULL,
`last_name` varchar(50) NOT NULL,
`first_name` varchar(50) NOT NULL,
`name_initials` varchar(45) NOT NULL,
PRIMARY KEY (`vendor_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
With the following insert statement:
INSERT INTO `vendor_contacts`
VALUES (5,'Davison','Michelle',''),
(12,'Mayteh','Kendall',''),
(17,'Onandonga','Bruce',''),
(44,'Antavius','Anthony',''),
(76,'Bradlee','Danny',''),
(94,'Suscipe','Reynaldo',''),
(101,'O\'Sullivan','Geraldine',''),
(123,'Bucket','Charles','');
I would like to run a query that extracts the first letter from the first name and last name columns.
SELECT vendor_id, last_name, first_name, substring(first_name, 1, 1) AS initials
FROM vendor_contacts;
The following guide http://www.w3resource.com/mysql/string-functions/mysql-substring-function.php, only shows how to work with one column.
You pull them separately and combine them using concat():
SELECT vendor_id, last_name, first_name,
CONCAT(LEFT(first_name, 1), LEFT(last_name, 1)) as initials
FROM vendor_contacts;
Related
In one table I have a list of cities and in another a list of clients. On clients I have a varchar column identifiend a list of cities separated by commas (ex: "2,3,4").
When I tried to list the cities of a client it is shown just the first city of the list.
It seem that is adding some quotation marks on the value like:
select GROUP_CONCAT(city.name)
from city where city.id_city in ('2,3,4')
¿How can avoid this situacion?
https://dbfiddle.uk/?rdbms=mysql_5.6&fiddle=a70c667e820c3208053b324075b0462c
CREATE TABLE `city` (
`id_city` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id_city`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `client` (
`id_client` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`cities` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id_client`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO city (id_city,name) VALUES ('1','New York');
INSERT INTO city (id_city,name) VALUES ('2','Boston');
INSERT INTO city (id_city,name) VALUES ('3','San Diego');
INSERT INTO city (id_city,name) VALUES ('4','Seatle');
INSERT INTO city (id_city,name) VALUES ('5','Chicago');
INSERT INTO client (id_client,name,cities) VALUES ('1','Client_1','2,3,4');
select client.id_client, client.name, (select GROUP_CONCAT(city.name)
from city where city.id_city in (client.cities)) as cities from client;
You cannot directly pass the list to your queries. You need to change your code to -
SELECT client.id_client,
client.name,
(SELECT GROUP_CONCAT(city.name)
FROM city
WHERE FIND_IN_SET(city.id_city, client.cities) <> 0) AS cities
FROM client;
DB Fiddle.
Though this solves your purpose, I think you must consider visiting this link which clearly says that storing the comma-separated values is really a very bad idea.
I have one to many table relationship :
one user for multiple event
one event for multiple event_attribute
Now, I group by userId and want to know how many for each event attribute ?
I am using group_concat like this:
group_concat(
concat(event_event_attribute.event_attr_id,
count( distinct event_event_attribute.value)
) group by event_attr_id)
)
group by userId
So here, I first group by userId, then group concat event-attribute, at least I hope to have :
(attr1, 10),(attr2, 30)....
all in one row.
But this does not work at all
Any suggestions?
To be more specific, this is the DB schema I am using:
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
);
CREATE TABLE `event` (
`id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `event_attr` (
`id` int(11) NOT NULL,
`att_name` varchar(45) DEFAULT NULL,
`event_id` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `user` VALUES (1,'user1'),(2,'user2'),(3,'user3');
INSERT INTO `event` VALUES (1,'event1',1),(2,'event2',1),(3,'event3',1),(4,'event4',2),(5,'event5',2),(6,'event6',3);
INSERT INTO `event_attr` VALUES (1,'att1','1'),(2,'att2','1'),(3,'att3','1'),(4,'att1','2'),(5,'att2',NULL);
Now if I am running:
select u.id, group_concat(e.name)
from user u
join event e on u.id=e.user_id
group by u.id
I will get:
1 event1,event2,event3
2 event4,event6
3 event 6
That is fine. But one step forward, I need to know count for each event_attt for each user, such as:
1 evet_att1:3;event_att2:2
2 event_att3:1
Then it is not possible. Can I use just one query to get above expected response?
should be the inverse alias concat the aggreagted values and not aggregated the concat
select concat (group_concat(event_event_attribute.event_attr_id )
,' - ',
count( distinct event_event_attribute.value) )
from event_event_attribute
group by userid
Otherwise could be you need an subquery for obtain the count group by event_attr_id
select group_concat(
concat(event_attr_id), ',', count_value)
)
from t (
select user_id, event_event_attribute.event_attr_id, count( distinct event_event_attribute.value) count_value
from event_event_attribute
group by event_attr_id
) t
group by user_id
I'm trying to retrieve values by joining two tables (the customer and enquiry table),then i'm trying to store the retrieved values into another table that would come in handy for reasons irrelevant here.And then i'm finally deleting the retrieved values from the enquiry table. When i'm trying to execute the stored procedure i'm getting the following error shown in the screenshot below.
how do i resolve this error?
Stored Procedure:-
CREATE PROCEDURE `backup_eq`(
IN `eq` VARCHAR(15), IN `mail` VARCHAR(30), IN `dates` DATE, IN `cmp` VARCHAR(10), IN `rea` VARCHAR(50))
NOT DETERMINISTIC MODIFIES SQL DATA SQL SECURITY DEFINER
BEGIN
SELECT eqno into #eno,Date1 into #d,cmpname into #c,subject into #s,cid into #cd
FROM `enquiry` NATURAL JOIN `customer`
WHERE eqno=eq and email=mail and cmpname=cmp and Date=dates;
INSERT INTO `enquiryBin`(`Eqno`, `Date1`, `Cmpname`, `Subject`, `CID`, `Reason`)
VALUES (#eno,#d,#c,#s,#cd,rea);
DELETE FROM `enquiry`
WHERE eqno=eq and cid=#cd and cmpname=cmp and Date1=dates;
END
The create table statements of the two tables are given below
CREATE TABLE `customer` (
`CID` int(15) NOT NULL,
`Address` varchar(100) NOT NULL,
`Name` varchar(20) NOT NULL,
`email` varchar(30) NOT NULL,
`phone` bigint(20) NOT NULL
)
ALTER TABLE `customer`
ADD PRIMARY KEY (`CID`);
CREATE TABLE `enquiry` (
`Eqno` varchar(15) NOT NULL,
`Date1` date NOT NULL,
`Cmpname` varchar(10) NOT NULL,
`Subject` varchar(100) NOT NULL,
`CID` int(15) NOT NULL
)
ALTER TABLE `enquiry`
ADD PRIMARY KEY (`Eqno`,`Cmpname`,`CID`,`Date1`)
SELECT eqno into #eno,Date1 into #d,cmpname into #c,subject into #s,cid into #cd
Should be
SELECT eqno, Date1, cmpname, subject, cid INTO #eno, #d, #c, #s, #cd
That is, name all columns in the select-list separately from the INTO clause.
Refer to syntax documentation: https://dev.mysql.com/doc/refman/5.7/en/select-into.html
There's no need for all those variables, just use an INSERT INTO ... SELECT query, and a JOIN in the DELETE query.
INSERT INTO enquiryBin (`Eqno`, `Date1`, `Cmpname`, `Subject`, `CID`, `Reason`)
SELECT eqno, Date1, cmpname, subject, cid, rea
FROM FROM `enquiry` NATURAL JOIN `customer`
WHERE eqno=eq and email=mail and cmpname=cmp and Date1 = dates;
DELETE e FROM enquiry AS e
NATURAL JOIN customer
WHERE eqno = eq AND email = mail AND cmpname = cmp AND Date1 = dates
I am currently collecting lap times in a sql database and are having some difficulties with extracting the drivers with fastest laptimes!
The structure looks like the following!
CREATE TABLE IF NOT EXISTS `leaderboard` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`driver` varchar(50) NOT NULL,
`car` varchar(50) NOT NULL,
`best` double NOT NULL,
`guid` bigint(255) NOT NULL,
`server_name` varchar(255) NOT NULL,
`track` varchar(55) NOT NULL,
PRIMARY KEY (`id`),
KEY `driver` (`driver`),
KEY `server_name` (`server_name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1213 ;
Data example
INSERT INTO `leaderboard` (`id`, `driver`, `car`, `best`, `guid`, `server_name`, `track`) VALUES
(1, 'dave.38', 'bmw_m3_e30', 88.379, 76561198084629688, 'A++%21+A++%21+------+Saturdaynightracing.tk+-+%5BRACE-SERVER%5D+-+%5BMagione%5D+%23SNR', 'magione'),
(2, 'Gabriel PorfÃrio', 'bmw_m3_e30', 87.318, 76561197987062834, 'A++%21+A++%21+------+Saturdaynightracing.tk+-+%5BRACE-SERVER%5D+-+%5BMagione%5D+%23SNR', 'magione'),
(3, 'xX_VEGA_Xx', 'bmw_m3_e30', 88.23, 76561198182074333, 'A++%21+A++%21+------+Saturdaynightracing.tk+-+%5BRACE-SERVER%5D+-+%5BMagione%5D+%23SNR', 'magione'),
(4, 'dave.38', 'bmw_m3_e30', 88.379, 76561198084629688, 'A++%21+A++%21+------+Saturdaynightracing.tk+-+%5BRACE-SERVER%5D+-+%5BMagione%5D+%23SNR', 'magione'),
(5, 'Gabriel PorfÃrio', 'bmw_m3_e30', 87.318, 76561197987062834, 'A++%21+A++%21+------+Saturdaynightracing.tk+-+%5BRACE-SERVER%5D+-+%5BMagione%5D+%23SNR', 'magione');
Now i am trying to sort out the drivers with best time using column best using the following SQL but it appears as if some times are discarded, the combination of sort and order does not work.
SELECT DISTINCT guid, car, best, driver FROM `leaderboard` WHERE `server_name` like '%%' AND `track` = 'magione' GROUP BY(driver) ORDER BY `best` * 1 LIMIT 10
Please help this is driving me mad!
Some fields in your data are not very clear, so I made such assumptions:
guid means driver's guid (because it is the same for the same driver in your data).
car is the same for the same driver.
With these assumptions you can use simple GROUP BY to get the results that you need:
SELECT driver, car, MIN(best) as best_time, guid
FROM leaderboard
WHERE `server_name` like '%%' AND `track` = 'magione'
GROUP BY driver, car, guid
ORDER BY MIN(best)
I'd like to collect data from 2 different mysql tables ordering the result by a timestamp but without merging the columns of the 2 tables in a single row.
T_ONE(one_id,one_someinfo,one_ts)
T_TWO(two_id,two_otherinfo,two_ts)
Notice that the field two_otherinfo is not the same as one_someinfo, the only columns in common are id and timestamp.
The result should be a mix of the two tables ordered by the timestamp but each row, depending on the timestamp, should contain only the respective columns of the table.
For example, if the newest record comes from T_TWO that row should have the T_ONE one_someinfo column empty.
I just need to order the latest news from T_ONE and the latest messages posted on T_TWO so the tables are not related. I'd like to avoid using 2 queries and then merging and ordering the results by timestamp with PHP. Does anyone know a solution to this? Thanks in advance
This is the structure of the table
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL auto_increment,
`fromid` int(10) NOT NULL,
`toteam` int(10) NOT NULL,
`banned` tinyint(1) NOT NULL default '0',
`replyid` int(15) default NULL,
`cont` mediumtext NOT NULL,
`timestamp` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE `stars` (
`id` int(10) unsigned NOT NULL auto_increment,
`daynum` int(10) NOT NULL,
`userid` int(10) NOT NULL,
`vote` tinyint(2) NOT NULL default '3',
`timestamp` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `posts` (`fromid`, `toteam`, `banned`, `replyid`, `cont`, `timestamp`) VALUES(5, 12, 0, 0, 'mess posted#1', 1222222220);
INSERT INTO `posts` (`fromid`, `toteam`, `banned`, `replyid`, `cont`, `timestamp`) VALUES(5, 12, 0, 0, 'mess posted#2', 1222222221);
INSERT INTO `posts` (`fromid`, `toteam`, `banned`, `replyid`, `cont`, `timestamp`) VALUES(5, 12, 0, 0, 'mess posted#3', 1222222223);
INSERT INTO `stars` (`daynum`, `userid`, `vote`, `timestamp`) VALUES(3, 160, 4, 1222222222);
INSERT INTO `stars` (`daynum`, `userid`, `vote`, `timestamp`) VALUES(4, 180, 3, 1222222224);
The result ordering by timestamp DESC should be the second record of table stars with timestamp 1222222224 then the third record of table posts with timestamp 1222222223 and following... Since the tables have got different fields from each other, the first row of the result should contain the columns of the table stars while the columns of table posts should be empty.
The columns of a UNION must be the same name and datatype on every row. In fact, declare column aliases in the first UNION subquery, because it ignores any attempt to rename the column in subsequent subqueries.
If you need the columns from the two subqueries to be different, put in NULL as placeholders. Here's an example, fetching the common columns id and timestamp, and then fetching one custom column from each of the subqueries.
(SELECT p.id, p.timestamp AS ts, p.fromid, NULL AS daynum FROM posts)
UNION
(SELECT s.id, s.timestamp, NULL, s.daynum, FROM stars)
ORDER BY ts DESC
Also put the subqueries in parentheses, so the last ORDER BY applies to the whole result of the UNION, not just to the last subquery.
SELECT one_id AS id, one_someinfo AS someinfo, one_ts AS ts
UNION
SELECT two_id AS id, two_someinfo AS someinfo, two_ts AS ts
ORDER BY ts
SELECT one_id AS id
, one_someinfo AS one_someinfo
, NULL AS two_someinfo
, one_ts AS ts
FROM t_ONE
UNION ALL
SELECT two_id
, NULL
, two_someinfo
, two_ts
FROM t_TWO
ORDER BY ts