i want to fetch duplicate data from the database but the problem is:
i have userids in an array like :
1235, 1235, 5468, 84321, 1235
i used implode and to make that array in string in implement into the database like:
"select * from tbl_name where userid in ('" . $implode_arr . "') limit 0, 10";
which is give me the result like 1235, 5468, 84321 but i want all the data, solution for this is simply run the query in the FOR LOOP or else
but i want same because i add the pagination within the query.
I don't want any code because its already working but the problem is to add pagination Please help to resolve the problem :(
It sounds like you want to join in the user data into this query. You can do that using a LEFT JOIN like this:
SELECT *
FROM tbl_name
LEFT JOIN database_name.user ON database_name.user.id = tbl_name.userid
WHERE userid IN (...)
LIMIT 0, 10
This is assuming your users are stored in the user table in the database_name database, and that the user table has an id field which matches up to the tbl_name field userid. If your fields or table names are different, just change them in this query. In PHP that would be:
"SELECT * FROM tbl_name LEFT JOIN database_name.user ON database_name.user.id = tbl_name.userid WHERE userid IN ('" . $implode_arr . "') LIMIT 0, 10"
Note that to connect two databases, both must be accessible by your same connected user.
Try this it would also work as expected
select * from tbl_name where FIND_IN_SET(user_id,'1235, 1235, 5468, 84321, 1235
') limit 1,10
Check this to remove duplicates
Related
I have a column named id with a bunch of ids separated by commas like this:
asdaxxdfd2,wwfsfdssdfsd6,sdfdsfdsed2,23445rr55
I need to match an id from the column to an existing $user_id
Trying this didn't do it:
"SELECT id FROM my_table WHERE id LIKE '%" . $user_id . "%'";
Not sure what else I can do.
Thank you.
"SELECT id FROM my_table WHERE concat(',', id, ',') LIKE '%," . $user_id . ",%';"
should do it.
But I also strongly recommend to normalize the schema.
Your question is a little bit ambiguous, I don't know if this solution is what you intends:
SELECT REGEXP_SUBSTR(id, '[^,]+', 1, 1) COLUMN_1,
REGEXP_SUBSTR(id, '[^,]+', 1, 2) COLUMN_2,
FROM my_table;
or just
SELECT id
FROM my_table
WHERE id LIKE '%wwfsfdssdfsd6%'
SELECT REGEXP_SUBSTR(id," . $user_id . ") UserID FROM my_table;
This will return the matching user id but again using a database with values stored in a single row is never a good idea.
SELECT * FROM tbl WHERE id REGEXP "[[:<:]]$user_id[[:>:]]";
Those match "word boundaries", thereby handling beginning and end of string.
But, without normalizing there is no way to make a query that runs faster than a full table scan.
I have two tables, one is a user log which stores the user by number
timestamp / user_id / transaction_id / amount
the other is a user table which has the users number and their full name
user_id / fullname
I want to select the entire user log and display it, but instead of displaying their number, display their full name from the other table, but I can't get it working. I keep modifying the sql and breaking it. Is there a way to accomplish this with php postgresql or should I use a function?
I keep getting an error that user_id is integer and the fullname is not
Please assist.
$query = "SELECT * FROM user_log
INNER JOIN user_staff
ON user_log.user_id=user_staff.user_name
ORDER BY user_log_id DESC LIMIT 200;";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['timestamp'], htmlspecialchars($myrow['user_id']), htmlspecialchars($myrow['transaction_id']), htmlspecialchars($myrow['amount']));
}
?>
Use this query:
SELECT "timestamp", fullname, transaction_id, amount
FROM user_log
JOIN users USING (user_id)
Note that "timestamp" is a SQL reserved word and you should not use it for a column name. If you must use it, put it in double quotes.
Perhaps something like:
SELECT user_log.timestamp, users.fullname, user_log.transaction_id, user_log.amount
FROM user_log
INNER JOIN users
ON users.user_id=user_log.user_id
ORDER BY user_log_id
DESC LIMIT 200;
You can read up on SQL Joins here: http://www.w3schools.com/sql/sql_join.asp
I am a newbie in PHP/MySQL and this is my first question on stackoverflow, so please ignore any mistake if I have made any.
I am trying to get records from a table through this query.
$CId = $this->input->post('Child_id'); //child_id is the value from a textfield
$r_detail = ("SELECT *
FROM `result_details`
WHERE ResultId
IN (SELECT Result_Id
FROM `results`
WHERE childId = '".$CId." ') " );
this query is returning an empty $r_detail. However when I query the same statement in PHPMyAdmin in localhost and change "$CID" to a number, I get the desired records.
Any Help will be much appreciated.
You have a space in INNER JOIN WHERE: '".$CId." ' should be '".$CId."'.
$r_detail = ("SELECT *
FROM `result_details`
WHERE ResultId
IN (SELECT Result_Id
FROM `results`
WHERE childId = '".$CId." ') " );
has just string...you need to call some db function to get the data such as in code igniter may be
$this->db->query($r_detail);
I have two different tables where I need to fetch the list of store ids from one table and then find the list of coupons for those store ids.
Currently,
SELECT `storename` FROM `stores` where `brandname` = 21
This will return something like
Store 1
Store 2
Store 3
Store 4
And I need to to run another query like
SELECT * FROM `coupons` where `storename` = {{All these stores}}
I can't use while loops because, the number of stores comes from first query can't be determined and the the output I want was not coming as expected while using while loop as I am trying to do something like
while(first query output get storename)
{
do query here
while(second query output get all coupons per store)
{
// All coupons display here.
}
}
This is making quite complicated as well, is there anyway that I can tweak my SQL query and get results easily?
Thanks
you can use this query:
SELECT * FROM `coupons`
where `storename` IN (
SELECT `storename` FROM `stores` where `brandname` = 21);
$query = 'SELECT t.storename, h.couponid AS couponsid, h.coupon AS couponvalue'
. ' FROM #__stores AS t'
. ' LEFT JOIN #__coupons AS h ON h.storename = t.storename'
. ' where `brandname` = 21'
. ' ORDER BY anything you like'
;
I have two primary MySQL tables (profiles and contacts) with many supplementary tables (prefixed by prm_). They are accessed and manipulated via PHP.
In this instance I am querying the profiles table where I will retrieve an Owner ID and a Breeder ID. This will then be referenced against the contacts table where the information on the Owners and Breeders is kept.
I received great help here on another question regarding joins and aliases, where I was also furnished with the following query. Unfortunately, I am having huge difficulty in actually echoing out the results. Every single site that deals with Self Joins and Aliases provide lovely examples of the queries - but then skip to "and this Outputs etc etc etc". How does it output????
SELECT *
FROM (
SELECT *
FROM profiles
INNER JOIN prm_breedgender
ON profiles.ProfileGenderID = prm_breedgender.BreedGenderID
LEFT JOIN contacts ownerContact
ON profiles.ProfileOwnerID = ownerContact.ContactID
LEFT JOIN prm_breedcolour
ON profiles.ProfileAdultColourID = prm_breedcolour.BreedColourID
LEFT JOIN prm_breedcolourmodifier
ON profiles.ProfileColourModifierID = prm_breedcolourmodifier.BreedColourModifierID
) ilv LEFT JOIN contacts breederContact
ON ilv.ProfileBreederID = breederContact.ContactID
WHERE ProfileName != 'Unknown'
ORDER BY ilv.ProfileGenderID, ilv.ProfileName ASC $limit
Coupled with this is the following PHP:
$owner = ($row['ownerContact.ContactFirstName'] . ' ' . $row['ownerContact.ContactLastName']);
$breeder = ($row['breederContact.ContactFirstName'] . ' ' . $row['breederContact.ContactLastName']);
All details EXCEPT the contacts (gender, colour, etc.) return fine. The $owner and $breeder variables are empty.
Any help in settling this for me would be massively appreciated.
EDIT: My final WORKING query:
SELECT ProfileOwnerID, ProfileBreederID,
ProfileGenderID, ProfileAdultColourID, ProfileColourModifierID, ProfileYearOfBirth,
ProfileYearOfDeath, ProfileLocalRegNumber, ProfileName,
owner.ContactFirstName AS owner_fname, owner.ContactLastName AS owner_lname,
breeder.ContactFirstName AS breeder_fname, breeder.ContactLastName AS breeder_lname,
BreedGender, BreedColour, BreedColourModifier
FROM profiles
LEFT JOIN contacts AS owner
ON ProfileOwnerID = owner.ContactID
LEFT JOIN contacts AS breeder
ON ProfileBreederID = breeder.ContactID
LEFT JOIN prm_breedgender
ON ProfileGenderID = prm_breedgender.BreedGenderID
LEFT JOIN prm_breedcolour
ON ProfileAdultColourID = prm_breedcolour.BreedColourID
LEFT JOIN prm_breedcolourmodifier
ON ProfileColourModifierID = prm_breedcolourmodifier.BreedColourModifierID
WHERE ProfileName != 'Unknown'
ORDER BY ProfileGenderID, ProfileName ASC $limit
Which I could then output by:
$owner = ($row['owner_lname'] . ' - ' . $row['owner_fname']);
Many Thanks to All!
I guess you're using the mysql_fetch_array or the mysql_fetch_assoc-functions to get the array from the result-set?
In this case, you can't use
$row['ownerContact.ContactFirstName']
as the PHP-Docs read:
If two or more columns of the result have the same field names, the
last column will take precedence. To access the other column(s) of the
same name, you must use the numeric index of the column or make an
alias for the column. For aliased columns, you cannot access the
contents with the original column name.
So, you can either use an AS in your SQL-query to set other names for the doubled rows or use the numbered indexes to access them.
This could then look like this:
Using AS in your Query
In your standard SQL-query, the columns in the result-set are named like the columns which their values come from. Sometimes, this can be a problem due to a naming-conflict. Using the AS-command in your query, you can rename a column in the result-set:
SELECT something AS "something_else"
FROM your_table
This will rename the something-column to something_else (you can leave the ""-quotes out, but I think it makes it more readable).
Using the column-indexes for the array
The other way to go is using the column-index instead of their names. Look at this query:
SELECT first_name, last_name
FROM some_table
The result-set will contain two columns, 0 ==> first_name and 1 ==> last_name. You can use this numbers to access the column in your result-set:
$row[0] // would be the "first_name"-column
$row[1] // would be the "last_name"-column
To be able to use the column-index, you'll need to use mysql_fetch_row or the mysql_fetch_assoc-function, which offers an associative array, a numeric array, or both ("both" is standard).
you need to replace the * with the data you need , and the similar ones you have to make aliases too :
ownerContact.ContactFirstName as owner_ContactFirstName
and
breederContact.ContactFirstName as breeder_ContactFirstName .
like this :
select ownerContact.ContactFirstName as owner_ContactFirstName , breederContact.ContactFirstName as breeder_ContactFirstName from profiles join ownerContact ... etc
in this way you will write :
$owner = ($row['owner_ContactFirstName'] . ' ' . $row['owner_ContactLastName']);
$breeder = ($row['breeder_ContactFirstName'] . ' ' . $row['breeder_ContactLastName']);
You cannot specify table alias when you access row using php. Accessing it by $row['ContactFirstName'] would work if you didn't have 2 fields with the same name. In this case whatever ContactFirstName appears second overwrites the first.
Change your query to use fields aliases, so you can do $owner = $row['Owner_ContactFirstName'].
Another option I'm not 100% sure is to access field by index, not by name(e.g. $owner=$row[11]). Even if it works I don't recommend to do so, you will have a lot of troubles if change your query a bit.
On outer select You have only two tables:
(inner select) as ilv
contacts as breederContact
there is no ownerContact at all