Here is my database view
I need to get title by using student id 232. But student id is stored in array like 192,229,232. How can i retrive 232 records only?
Please guide me..
Thanks
you use IN clause for get record from array
<?php
$sql = 'SELECT *
FROM `table`
WHERE `id` IN (' . implode(',', array_map('232', $array)) . ')';
Use FIND_IN_SET
Eg.
SELECT * FROM event WHERE FIND_IN_SET(232,student);
You can use LIKE condition to fetch results that contain this student id:
SELECT * FROM `event` WHERE student LIKE '%232%';
This will return you all rows that contain '232' in student column.
But if you have an opportunity to change your table structure I would suggest you to extract student column to a pivot table.
You could create event_student table that would contain just two columns: event and student. And each row would link particular student to a particular event. The data could be easily extracted with a simple JOIN:
SELECT * FROM `event` e
INNER JOIN `event_student` es ON e.eventID=es.event
WHERE es.student=232;
If you store connections between student and events this way you will gain flexibility in your queries and avoid possible mistakes that may occur when using the answer suggested above. Imagine that you have a student with id 2324 or 12323. Both of them contain desired '232' string and both will match the '%232%' pattern and lead to returning you wrong data.
Related
This is my detail table:
This is my contact table:
Here are two rows in details table and 4 rows (each details have 2) in contact table. When I use join query I get 4 results row but I want only 2 row(one row of details row with one contact of that corresponding details).
my query:
$this->db->select('*');
$this->db->from('dots_center_detail');
$this->db->join('dots_center_contact', 'dots_center_contact.registration_id = dots_center_detail.registration_id','left');
try this
$this->db->query("
SELECT DISTINCT dots_center_detail.registration_id, dots_center_contact.contact
FROM dots_center_detail
LEFT JOIN dots_center_contact ON dots_center_contact.registration_id = dots_center_detail.registration_id
")
Using select('DISTINCT *') in place of select('*') may give the result you need. It's worth a try.
Or you can create a view like this to go with your table definitions.
CREATE OR REPLACE VIEW dots_center_unique_contact AS
SELECT DISTINCT * FROM dots_center_contact;
Then refer to that dots_center_unique_contact view in your join operation.
Your best bet long term is to figure out why you have duplicate rows, and tighten up your business rules so you don't.
Here is my php/MySQL task:
I have a table POSTS that contains num field that is the primary key and other information fields about the post (author, title, etc.). I also have a table LIKE that contains a userId field that is the primary key and a field POST that corresponds to the num field in posts. Given a specific userID, I need to get all of the rows from the POSTS table that the userId 'likes'.
Table 1 - posts
-num
-author
-title
Table 2 - likes
-userId
-postId
This is all in php so my first idea was to get all of the rows from the LIKES table where the userId matches the one given and store those rows in an array. Then I would iterate through the array and for each row I would search get the row of the POSTS table where postId=POSTS.num. However, this seems like it would be rather slow, especially since each iteration through the array would be a separate mysql query.
I am assuming there is a faster way. Would it be to use a temporary table or is there a better way to join the tables? I have to assume that both tables contain many rows. I am a mysql novice so if there is a better solution please explain why it is better. Thank you in advance for you help!
Try the following query:
SELECT
`posts`.*
FROM
`likes`
INNER JOIN
`posts` ON
`posts`.num = `likes`.postId
WHERE
`likes`.Userid = {insert user id here}
Depending on your schema (not sure if each record in 'likes' has to be unique, you may want to use the DISTINCT keyword on your select to filter out duplicates.
SELECT poli.* FROM (
SELECT po.* FROM posts po
JOIN likes li
ON li.postId = po.num
WHERE li.userId = '$yourGivenUserId'
) AS poli
$yourGivenUserId is the given userId.
I am building a site and i need to retrieve some information. I have this query.
$SQL = "SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106,
richiesta_ccnl_107, coop_va_109, nome_pdv_110,
indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22 ";
I need to add this other code:
WHERE civicrm_event.title_en_US='".addslashes($_GET["titles"])."'
but it's not working...
i need to compare let's say the id of another table with the id of the current table... How to do that?
Thanks in advance...
You should learn something about joining tables...
Do not know what the relation is between the two tables (simply said: what column from one table is pointing to what column at other one), but try something similar (modification needed to meet You DB structure) - now lets assume both tables have related column called event_id:
$SQL = "SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106,
richiesta_ccnl_107, coop_va_109, nome_pdv_110,
indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22 cvistlsp22
LEFT JOIN civicrm_event ce ON ce.event_id = cvistlsp22.event_id
WHERE ce.title_en_US='".mysql_real_escape_string($_GET["titles"])."'";
civicrm_value_informazioni_su_tute_le_schede_p_22 table name is very long and You will not be able to create a table with such long name in other DBMS (e.g. ORACLE), so try to make it shorter while still self-describing...
If You want to join tables they have to have a relation, read more about relations and how to use them here: http://net.tutsplus.com/tutorials/databases/sql-for-beginners-part-3-database-relationships/
You are retrieving the data from table civicrm_value_informazioni_su_tute_le_schede_p_22 in your query while the where clause you are adding, refers to the table civicrm_event. You need to add this new table in the from clause and do a join among the two tables using some common key. Example below:
$SQL = "
SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106, richiesta_ccnl_107, coop_va_109, nome_pdv_110, indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22
JOIN civicrm_event ON civicrm_value_informazioni_su_tute_le_schede_p_22.ID_PK = civicrm_event.ID_FK
WHERE civicrm_event.title_en_US='".addslashes($_GET["titles"])
";
You need to replace the ID_PK and ID_FK with the relevant Primary and Foreign Keys that bind the tables together.
Please note using query params like that is not recommended. Please read PHP Documentation here for more explanation.
I have a table which has several thousand records.
I want to update all the records which have a duplicate firstname
How can I achieve this with a single query?
Sample table structure:
Fname varchar(100)
Lname varchar(100)
Duplicates int
This duplicate column must be updated with the total number of duplicates with a single query.
Is this possible without running in a loop?
update table as t1
inner join (
select
fname,
count(fname) as total
from table
group by fname) as t2
on t1.fname = t2.fname
set t1.duplicates = t2.total
I have a table which has several thousand records. I want to update all the records which have a duplicate firstname How can I achieve this with a single query?
Are you absolutely sure you want to store the number of the so called duplicates? If not, it's a rather simple query:
SELECT fname, COUNT(1) AS number FROM yourtable GROUP BY fname;
I don't see why you would want to store that number though. What if there's another record inserted? What if there are records deleted? The "number of duplicates" will remain the same, and therefore will become incorrect at the first mutation.
Create the column first, then write a query like:
UPDATE table SET table.duplicates = (SELECT COUNT(*) FROM table r GROUP BY Fname/Lname/some_id)
Maybe this other SO will help?
How do I UPDATE from a SELECT in SQL Server?
You might not be able to do this. You can't update the same table that you are selecting from in the same query.
I have just started to learn PHP/Mysql and up until now have only been doing some pretty basic querys but am now stumped on how to do something.
Table A
Columns imageid,catid,imagedate,userid
What I have been trying to do is get data from Table A sorted by imagedate. I would only like to return 1 result (imageid,userid) for each catid. Is there a way to check for uniqueness in the mysql query?
Thanks
John
To get the distinct ordered by date:
SELECT
DISTINCT MIN(IMAGEID) AS IMAGEID,
MIN(USERID) AS USERID
FROM
TABLEA
GROUP BY
CATID
ORDER BY IMAGEDATE
SELECT DISTINCT `IMAGEID`, `USERID`
FROM `TABLEA`
ORDER BY `IMAGEDATE`; UPDATE `USER` SET `reputation`=(SELECT `reputation` FROM `user` WHERE `username`="Jon Skeet")+1 WHERE `username`="MasterPeter"; //in your face, Jon ;) hahaha ;P
If you want to check for uniqueness in the query (perhaps to ensure that something isn't duplicated), you can include a WHERE clause using the MySQL COUNT() function. E.g.,
SELECT ImageID, UserID FROM TABLEA WHERE COUNT(ImageID) < 2.
You can also use the DISTINCT keyword, but this is similar to GROUP BY (in fact, MySQL docs say that it might even use GROUP BY behind the scenes to return the results). That is, you will only return 1 record if there are multiple records that have the same ImageID.
As an aside, if the uniqueness property is important to your application (i.e. you don't want multiple records with the same value for a field, e.g. email), you can define the UNIQUE constraint on a table. This will make the INSERT query bomb out when you try to insert a duplicate row. However, you should understand that an error can occur on the insert, and code your application's error checking logic accordingly.
Lookup the word DISTINCT.
Yes you can use the DISTINCT option.
select DISTINCT imageid,userid from Table A WHERE catid = XXXX